package com.hspedu.newData.dmsxl.链表;

import com.hspedu.newData.dmsxl.ds.ListNode;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-27 
 * @Version: 1.0
 */

public class LC25K个一组翻转链表 {

    public ListNode reverseKGroup(ListNode head, int k) {

        ListNode dummy = new ListNode(0,head);

        ListNode pre = dummy;
        ListNode end = dummy;

        while (end.next!=null){

            for (int i = 0; i < k && end!=null; i++) {
                end = end.next;
            }
            if(end==null) break;

            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;

            pre.next = reverse(start);

            start.next = next;

            pre=start;
            end=start;
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode head){

        ListNode temp = null;

        while (head!=null){
            ListNode next = head.next;
            head.next = temp;
            temp = head;
            head = next;
        }
        return temp;
    }

}
